<?php

namespace app\admin\controller\auth;

use app\common\controller\Backend;
use fast\Tree;
use think\Cache;
use fast\Random;
use fast\Cols;
use fast\Date;

/**
 * 规则管理
 *
 * @icon fa fa-list
 * @remark 规则通常对应一个控制器的方法,同时左侧的菜单栏数据也从规则中体现,通常建议通过控制台进行生成规则节点
 */
class Rule extends Backend
{
    protected $model = null;
    protected $rulelist = [];
    protected $multiFields = 'ismenu,status';

    public function initialize()
    {
        parent::initialize();
        $this->model = model('AuthRule');
        // 必须将结果集转换为数组
        $ruleList = collection($this->model->order('weigh', 'desc')->select())->toArray();
        foreach ($ruleList as $k => &$v)
        {
            $v['title'] = __($v['title']);
            $v['remark'] = __($v['remark']);
        }
        unset($v);
        Tree::instance()->init($ruleList);

        $this->rulelist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'title');
        $ruledata = [0 => __('None')];
        foreach ($this->rulelist as $k => &$v)
        {
            if (!$v['ismenu'])
                continue;
            $ruledata[$v['itemid']] = $v['title'];
        }
        //print_r($ruledata);exit;
        $this->view->assign('ruledata', $ruledata);
    }

    public function index()
    {
      		$columnlist = Cols::columnread('authrule');
      		$flag = array();$options = array();
      		foreach($columnlist as $v){
      			$flag[] = $v['listorder'];
                  if($v['options']&&$v['isshowlist']==1){
                      //把带有选项的列，提取出来。
                      $options[$v['columnenname']] = $v['options'];
                  }
      		}
      		array_multisort($flag, SORT_ASC, $columnlist);
      		//设置过滤方法
      		$this->request->filter(['strip_tags']);
      		//如果发送的来源是Selectpage，则转发到Selectpage
      		if ($this->request->request('pkey_name')){
      			return $this->selectpage();
      		}
      		$searchfileds = array();
              $searchdefault = array();
      		$searchfileds['title'] = 'varcharshort';
              $searchfileds['pid'] = 'guid';
              $searchdefault['pid'] = '';
      		list($where, $sort, $order, $offset, $limit) = $this->buildparams($searchfileds,null,$searchdefault);
              $limit = 200;
      		$order = 'desc';
      		$sort = 'weigh';
      		$total = $this->model->where($where)->order($sort, $order)->count();
      		$totalpage = 1;$page = 1;
      		if($limit>0){
      				$totalpage = $total%$limit==0?intval($total/$limit):intval($total/$limit)+1;
      				//总页数
      				if($offset>0){$page = intval($offset/$limit)+1;}
      		}
              //print_r($where);exit;
      		$list = $this->model
      		->where($where)
      		->order($sort, $order)
      		->limit($offset, $limit)
      		->select();
              //print_r($list);exit;
      		for ($i = 0; $i < count($list); $i++) {
      				if(isset($list[$i]['category'])){
      					$list[$i]['catname'] = $list[$i]['category']['name'];
      				}
      				unset($list[$i]['intro']);unset($list[$i]['content']);
                      foreach ($options as $k => $v) {
                          if(isset($list[$i][$k])){
                              $arj = json_decode($v,true);
                              $sarj = isset($arj[$list[$i][$k]])?$arj[$list[$i][$k]]:"";
                              $list[$i][$k] = $sarj;
                          }
                      }
      				//$list[$i]['createtime'] = Date::timetodate($list[$i]['createtime'],3);
      				//$list[$i]['updatetime'] = Date::timetodate($list[$i]['updatetime'],3);
      		}
      		$result = array("total" => $total, "rows" => $list);
          $this->view->assign("lists",$result['rows']);
          $this->view->assign("listsjson",json_encode($result['rows']));
          $this->view->assign("columnlistjson",json_encode($columnlist));
          $this->view->assign("columnlist",$columnlist);
          $this->view->assign("total",$result['total']);
          $this->view->assign("offset",$offset);
          $this->view->assign("limit",$limit);
          $this->view->assign("totalpage",$totalpage);
          $this->view->assign("page",$page);
      		return $this->view->fetch('index');
	}
    /*
    //查看
    public function index()
    {
        if ($this->request->isAjax())
        {
            $list = $this->rulelist;
            $total = count($this->rulelist);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    */
    //添加
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params)
            {
                if (!$params['ismenu'] && !$params['pid'])
                {
                    $this->error(__('The non-menu rule must have parent'));
                }
                if($params['pid'] == '0'){
                    unset($params['pid']);
                }

                $params['icon'] = 'fa fa-table';
                $params['itemid'] = str_replace('-','',Random::uuid());
                //$result = $this->model->validate()->save($params);
                $result = $this->model->save($params);
                if ($result === FALSE){
                    $this->error($this->model->getError());
                }
                Cache::rm('__menu__');
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }
    //编辑
    public function edit($ids = NULL)
    {
        $row = $this->model->get(['itemid' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params)
            {
                if (!$params['ismenu'] && !$params['pid'])
                {
                    $this->error(__('The non-menu rule must have parent'));
                }
                if($params['pid'] == '0'){
                    unset($params['pid']);
                }
                //这里需要针对name做唯一验证
                $ruleValidate = \think\Loader::validate('AuthRule');
                $ruleValidate->rule([
                    'name' => 'require|format|unique:AuthRule,name,' . $row->itemid,
                ]);
                //$result = $row->validate()->save($params);
                $result = $row->save($params);
                if ($result === FALSE)
                {
                    $this->error($row->getError());
                }
                Cache::rm('__menu__');
                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            $delIds = [];
            foreach (explode(',', $ids) as $k => $v)
            {
                $delIds = array_merge($delIds, Tree::instance()->getChildrenIds($v, TRUE));
            }
            $delIds = array_unique($delIds);
            $count = $this->model->where('itemid', 'in', $delIds)->delete();
            if ($count)
            {
                Cache::rm('__menu__');
                $this->success();
            }
        }
        $this->error();
    }

}
